<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<!--    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">-->
    <link rel="stylesheet" href="./resoures/element-ui/index.css">
<!--    <link type="text/css" rel="stylesheet" href="../css/classifcation.css">-->
    <link type="text/css" rel="stylesheet" href="./css/classifcation.css">
    <!-- //引入vue.js -->
    <script src="./resoures/vue.js"></script>
    <!-- import JavaScript -->
<!--    <script src="https://unpkg.com/element-ui/lib/index.js"></script>-->
    <script src="./resoures/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="./resoures/axios.min.js"></script>
    <!-- 引入vue路由 -->
    <!--  <script src="https://cdn.staticfile.org/vue-router/2.7.0/vue-router.min.js"></script>-->
</head>
<body>
<div id="app">
    <div class="indexHead">
        <div class="catalogueLogo">
            <img src="./img/logo.png" height="70px">
        </div>
        <div class="title">
            网上书城
        </div>
        <div class="indexHeadText" >
            <a href="/index.html" class="indexHeadTextA">首页</a>
            <a href="/bookClassification" class="indexHeadTextA" >图书分类 </a>
            <a href="/" class="indexHeadTextA" v-if="!login">免费注册</a>
            <a href="/" class="indexHeadTextA" v-if="!login">请先登录</a>
            <a href="/shoping.html" class="indexHeadTextA" v-if="login" style="color: red;">购物车</a>
            <a href="/order.html" class="indexHeadTextA" v-if="login">我的订单</a>
            <a href="/" class="indexHeadTextA" v-if="login" @click="quit">退出</a>
        </div>
    </div>
    <hr style="margin-top: 40px;">

    <div class="Text" style="margin-left: 200px ">
        <el-table
                ref="multipleTable"
                :data="shoping"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="100"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="imageName"
                    label="图片"
                    width="200">
                <template slot-scope="scope">
                    <img :src="scope.row.imageName" style="width: 100%; height: auto;">
                </template>
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="图书名称"
                    width="200">
            </el-table-column>
            <el-table-column
                    prop="author"
                    label="作者"
                    width="200">
            </el-table-column>
            <el-table-column
                    prop="price"
                    label="价格"
                    width="120">
            </el-table-column>
            <el-table-column
                    label="数量"
                    width="200">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.quantity" type="number" :min="1" placeholder="请输入数量,默认为1"></el-input>
                </template>
            </el-table-column>
            <el-table-column
                    prop="bookId"
                    label="书ID"
                    width="120">
            </el-table-column>
        </el-table>
    </div>
    <div>
        <el-pagination
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                :total="total">
        </el-pagination>
        <div style="margin-top: 20px;margin-left: 500px">
            <el-button type="danger" round @click="buy">点击购买</el-button>
            <div v-if="loading" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(255, 255, 255, 0.8); padding: 20px; border-radius: 5px;">
                <span>加载中...</span>
            </div>
            <el-button type="danger" round @click="deleteByid">点击删除</el-button>
            <el-button @click="toggleSelection()">取消选择</el-button>
        </div>
    </div>

</div>
</body>
<script>
    const app = new Vue({
        el:'#app',
        data:{
            shoping:[{author:'',imageName:'',name:'',price:''}],
            multipleSelection: [],
            currentPage: 1,
            pageSize: 10, // 初始每页显示条数
            total: 20/* 总条数，可以根据实际情况进行设置 */,
            login:false,
            login_username:'',
            loading: false
        },
        computed:{
            filteredData() {
                // 根据 currentPage 和 pageSize 对数据进行分页
                const startIndex = (this.currentPage - 1) * this.pageSize;
                const endIndex = startIndex + this.pageSize;
                return this.tableData.slice(startIndex, endIndex);
            }
        },
        methods:{
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log("handleSelectionChange")
                console.log(this.multipleSelection)
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleCurrentChange(val) {
                // 当页码变化时更新 currentPage，并根据需要重新获取数据
                this.currentPage = val;
                console.log("handleCurrentChange")
                console.log(this.currentPage)
                this.search();
            },
            //判断登录状态
            checkLogin(){
                let token = sessionStorage.getItem("Linusername");
                return token !== null && token !== undefined;
            },
            //退出登录状态的事件
            quit(event){
                event.preventDefault();
                // 执行自定义逻辑
                alert("退出成功！")
                sessionStorage.removeItem("Linusername");
                location.href ="/index";
            },
            search(){
                // alert(this.login_username)
                _this = this;
                // 发起 GET 请求，并传入用户名称参数
                axios.get("http://localhost:8081/shopping", {
                    params: {
                        username: _this.login_username,
                        //当前页数
                        currentPage:_this.currentPage,
                        pageSize:_this.pageSize
                    }
                }).then(function (response) {
                    // 请求成功处理
                    console.log(response.data); // 响应数据
                    _this.shoping = response.data.shoping;
                    _this.total = response.data.size;
                    console.log("购物车内容为：")
                    console.log(_this.shoping)
                    console.log(_this.total)
                }).catch(function (error) {
                        // 请求失败处理
                        alert(error);
                    });
            },
            // searchPage(){
            //     _this = this;
            //     // 发起 GET 请求，并传入用户名称参数
            //     axios.get("http://localhost:8081/shoppingPage", {
            //         params: {
            //             username: _this.login_username,
            //             //当前页数
            //             currentPage:_this.currentPage,
            //             //总数据
            //         }
            //     }).then(function (response) {
            //         // 请求成功处理
            //         console.log(response.data); // 响应数据
            //         _this.shoping = response.data;
            //         console.log("购物车内容为：")
            //         console.log(_this.shoping)
            //     }).catch(function (error) {
            //         // 请求失败处理
            //         alert(error);
            //     });
            // },
            buy(){
                this.loading = true;
                const selectedRows = this.$refs.multipleTable.selection;
                if (selectedRows.length === 0) {
                    this.open4();
                    return; // 终止方法执行
                }// 获取选中的行数据
                const purchaseList = selectedRows.map(row => ({
                    id: row.id, // 图书id
                    name: row.name,
                    price: row.price, // 图书价格
                    quantity: row.quantity || 1, // 图书数量，默认为1
                    bookId: row.bookId
                }));
                console.log(purchaseList);
                const username = this.login_username;
                //生成订单
                // 发送请求到服务器
                axios.post("http://localhost:8081/gobuy", {
                    username: username,
                    purchases: purchaseList
                }).then(response => {
                    // 请求成功处理
                    console.log(response.data.success); // 响应数据
                    _this.open2();
                    //删除购物车的数据
                    _this.deleteByid();
                    // 可以进行进一步的处理，例如更新界面或显示成功消息
                }).catch(error => {
                    // 请求失败处理
                    alert(error);
                    alert("失败")
                }).finally(() => {
                    this.loading = false; // 请求完成后设置为false
                });

            },
            open1() {
                this.$message({
                    message: '成功',
                    type: 'success'
                });
            },
            open2() {
                this.$message({
                    message: '恭喜你，购买成功',
                    type: 'success'
                });
            },
            open4() {
                this.$notify.error({
                    title: '错误',
                    message: '请选择商品'
                });
            },
            deleteByid(){
                const selectedRows = this.$refs.multipleTable.selection; // 获取选中的行数据
                if (selectedRows.length === 0) {
                    this.open4();
                    return; // 终止方法执行
                }
                const selectedIds = selectedRows.map(row => row.id).join(","); // 获取选中行的 id 值并连接成字符串
                console.log("选中的id值为：" + selectedIds);
                // 发送请求给后端进行处理
                axios.get("http://localhost:8081/deleteshoping", {
                    params: {
                        ids: selectedIds,
                    }
                }).then(function (response) {
                    // 请求成功处理
                    console.log(response.data); // 响应数据
                    if (response.data.code ===1){
                        // 刷新购物车数据或者进行其他操作
                        _this.open1();
                        _this.search();
                        // location.reload()
                    }else {
                        alert("删除失败")
                    }

                }).catch(function (error) {
                    // 请求失败处理
                    alert(error);
                });
            }
        },
        mounted() {
            //判断登陆状态 首先获取名为"Linusername"的会话存储数据
            if (this.checkLogin()){
                this.login = true
                this.login_username = sessionStorage.getItem("Linusername")
            }
            this.search();
        },
    })
</script>
</html>